from pandas import DataFrame
from tools.base_tools import timestamp_to_string
from api_push.base_push import PushData
from tools.base_tools import fetch_data
from loguru import logger


def create_dataframe(data):
    df = DataFrame(data)
    df["payway"] = df["payway"].astype(int)
    return df


def replace_values(df, replacements):
    """
    这个函数根据一个替换字典在 DataFrame 中替换值。

    参数:
    df (pandas.DataFrame): 需要替换值的 DataFrame。
    replacements (dict): 一个字典，其中键是列名，值是字典，这个字典的键是旧值，值是新值。

    返回:
    pandas.DataFrame: 替换值后的 DataFrame。

    示例:
    ```python
    import pandas as pd

    # 创建一个样本 DataFrame
    df = pd.DataFrame({
        'A': [1, 2, 3],
        'B': ['a', 'b', 'c']
    })

    # 定义替换字典
    replacements = {
        'A': {1: 100, 3: 300},
        'B': {'a': 'alpha', 'c': 'gamma'}
    }

    # 使用这个函数
    df = replace_values(df, replacements)
    print(df)
    # 输出:
    #      A      B
    # 0  100  alpha
    # 1    2      b
    # 2  300  gamma
    ```
    """
    for column, replace_dict in replacements.items():
        if column in df.columns:
            df[column] = df[column].replace(replace_dict)
    return df


# 核心类,后期的点击行为的获取也是用类似的逻辑
class OrdersPush(PushData):
    def __init__(self, start_date, end_date, table_name):
        super().__init__(start_date, end_date, table_name)

    # 定义好提取单天的逻辑
    def get_one_day_data(self, day_str):
        # 配置信息
        url_orders = f"https://scapi.tayunapi.com/funcLog/orderList?pwd=JAT9voGxoxj7&start={day_str}&end={day_str}"
        #  需要根据in_type进行过滤就走这个逻辑
        # url_orders = f"https://scapi.tayunapi.com/funcLog/orderList?pwd=JAT9voGxoxj7&start={day_str}&end={day_str}&in_type=1045"
        # 获取并处理订单数据

        orders_data = fetch_data(url_orders)
        if not len(orders_data["list"]):
            return DataFrame()
        df_orders = create_dataframe(orders_data["list"])

        replacements = {
            "from": {3: "安卓", 4: "IOS"},
            "payway": {
                3: "微信支付",
                4: "支付宝",
                5: "苹果支付",
            },
            "buy_type": {
                11: "购买VIP",
                22: "购买素材包",
                33: "购买文章",
                44: "购买积分",
            },
            "status": {1: "待处理", 2: "成功", 3: "失败", 4: "退款", 5: "部分退款"},
        }
        df_orders = replace_values(df_orders, replacements)
        # create_time 字段是 1716134402 这种时间戳格式，需要转换为正常时间格式
        df_orders["real_amount"] = df_orders["real_amount"].astype(float)
        df_orders["create_time_format"] = df_orders["create_time"].apply(
            timestamp_to_string
        )
        return df_orders

    # 定义是否匹配,如果不需要匹配的话,这个就不用写了
    def pipei(self, df_orders):
        # 获取充值入口数据并合并
        # 匹配订单的类型
        url_in_type = "https://scapi.tayunapi.com/funcLog/conf?type=1"
        in_type_data = fetch_data(url_in_type)
        df_in_type = DataFrame(in_type_data)
        df_in_type.rename(columns={"id": "in_type_id"}, inplace=True)
        df_orders = df_orders.merge(
            df_in_type[["in_type_id", "key", "title"]],
            left_on="in_type",
            right_on="in_type_id",
            how="left",
        )
        # 删除 in_type_id 列
        df_orders.drop(columns="in_type_id", inplace=True)
        return df_orders


if __name__ == "__main__":
    push = OrdersPush("2024-05-28", "2024-06-04", "pay")
    push.push_mysql()
